<?php

header("Content-type: text/html; charset=utf-8");

$oper = $_POST['oper'];

if (!isset($oper) || !isset($_POST['eid']))
{
    die("Unknown command");
}

$admin = true;
require_once('auth_req.inc.php');

switch ($oper)
{
    case 'store':

      try
      {
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $dbh->beginTransaction();

        if ($_POST['eid'] == 0)     
        {                           // first insert new script and get id
            $sth = $dbh->prepare('insert into events set name=:name');
            $sth->bindParam(':name',$_POST['name']);    
            $sth->execute();

            $event_id = $dbh->lastInsertId();

        }
        else
        {                           // remove all old eid data

            $sth = $dbh->prepare('update events set name=:name where e_id=:eid');
            $sth->bindParam(':eid',intval($_POST['eid']), PDO::PARAM_INT);    
            $sth->bindParam(':name',$_POST['name']);    
            $sth->execute();

            $sth = $dbh->prepare('delete from event_items where e_id=:eid');
            $sth->bindParam(':eid',intval($_POST['eid']));    
            $sth->execute();

            $event_id = intval($_POST['eid']);
                
        }

        $griddata = json_decode(stripcslashes($_POST['grid']));

        $query = 'insert into event_items (e_id, c_id, prog) values ';

        $ins_comma = false;

        foreach($griddata as $key => $val)
        {
            print_r($val);

            if($ins_comma)
            {
                $query .= ',';
            }

            switch ($val->prog)
            {
                case 'ЖМ':
                    $prog= 9;
                break;
                case 'ОС':
                    $prog= 10;
                break;
                default:
                    $prog = intval($val->prog);
                break;
            }

            $query .= '('.$event_id.','.$val->c_id.','.$prog.')';
            $ins_comma = true;
        }

        $dbh->query($query);

        $dbh->commit();

      }
      catch (Exception $e)
      {
         $dbh->rollBack();
      }

    break;

    case 'del':

      try
      {
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $dbh->beginTransaction();
        
        $sth = $dbh->prepare('delete from event_items where e_id=:eid');
        $sth->execute(array('eid'=>intval($_POST['eid'])));

        $sth = $dbh->prepare('delete from events where e_id=:eid');
        $sth->execute(array('eid'=>intval($_POST['eid'])));
        
        $dbh->commit();
      }
      catch (Exception $e)
      {
         $dbh->rollBack();
      }


  break;

}

?>